/**
 * 	 data-initable="yes"    未指定参数时，需要处理的表格标识
 *	 data-paginationId=""   页面内的分页栏模版的id
 *   data-paginationUrl=""	分页栏的模版地址			
 *   data-toolBarId=""			工具栏的模版id
 *   data-toolBarUrl=""			工具栏的模版地址
 *   data-height=""					表格的高度
 *   data-minHeight=""			表格内容区的最小高度
 * 
 * 单个表格初始化可使用 new MaxTable(jdom);jdom为jQuery，或dom对象
 * 单个表格根据参数重置表格
 * 	var Ot = new MaxTable(jdom);
 * 	Ot.reflesh(height);
 * 多表格可以使用MaxTableInit(connection); connection为jQuery对象的集合
 * 
 * V0.6 说明：
 * 	1、新增表头的模拟点击事件，
 * 		只支持 给原table绑定onclick，ondblclick,onchange等事件
 * 		不支持jquery绑定的事件
 *  2、当MazTableInit方法没有传参数时，默认调用页面内所有的table[data-initable='yes']的集合
 * 	3、原表格保留，通过jQuery的wrap，before,after等方法改变其html所在的位置
 * 	4、可通过外部修改原表格的data-height的高度来做浏览器的自适应
 * 	5、
 * 
 *	Ahthor：MaxJh
 * 	Copyright：MaxJh
 * 	Version：v0.6
 */
;(function(win,$){
	var OTable = function(obj){
		this.target = $(obj);
		this.hasCaption = this.target.find("caption").length>0?true:false;
		this.hasThead = this.target.find("thead").length>0?true:false;
		this.hasTfoot = this.target.find("tfoot").length>0?true:false;
		this.initStyle();
		this.initParm();
		this.tableWraper = $("<div class='maxTableWarper'></div>"); 
		this.toolbar = $("<div class='maxTable_toolbar'></div>");
		this.caption = $("<div class='maxTable_caption'></div>");
		this.container = $("<div class='maxTable_container'></div>");
		this.header = $("<div class='maxTable_header'></div>");
		this.body = $("<div class='maxTable_body'></div>");
		this.footer = $("<div class='maxTable_footer'></div>");
		this.pagination = $("<div class='maxTable_pagination'></div>");
		this.getClass();
		this.getId();
		this.iniTable();
		return this;
	};
	
	OTable.CSSSTYLE = "<style id='tableInitSty'>"+
						".maxTable_container {position: relative;border: 1px solid #ddd;}"+
						".maxTable_header{position:absolute;top:0;left:0;right:0px;background:#ebebeb;}"+
						".maxTable_header>table {background: #cbcbcb;}"+
						".maxTable_caption>.table,.maxTable_header>.table,.maxTable_body>.table,.maxTable_footer>.table{margin-bottom:0px!important;}"+
						".maxTable_caption{margin-bottom:-1px;}"+
						".maxTable_body{overflow-y:auto;min-height:140px;}"+
						".maxTable_footer{position:absolute;left:0;right:0px;bottom:0px;background:#ebebeb;}"+
						".maxTable_pagination{padding-top:6px;clear:both;zoom:1;overflow:hidden;}"+
						".maxTable_pagination .foot_nav{position:static;}"+
						"caption{background:#ddd;color:#333;text-indent:0.5em;}"+
					  "</style>";
	
	OTable.CHECKBOX_CLASS = {
		headCheckBox:"js_maxheadCheck",
		headTriggerCheckBox:"js_maxbodyCheckTrigger",
		bodyCheckBox:"js_maxbodyCheck"
	}
	
	OTable.prototype = {
		initStyle:function(){
			var head = $(document).find("head")
			if(head.find("style#tableInitSty").length == 0){
				head.append(OTable.CSSSTYLE);
			}
		},
		//根据属性获取参数
		getParmByAttr:function(attr){
			return this.target.attr("data-"+attr) || this.target.data(attr);
		},
		//初始化，从页面上获取设定的参数
		initParm:function(){
			var self = this;
			self.config = {};
			self.config.height = self.getParmByAttr("height");											//表格的高度
			self.config.paginationUrl = self.getParmByAttr("paginationUrl");				//分页栏模版id，优先级大于url
			self.config.paginationId = self.getParmByAttr("paginationId");  				//分页栏模版url
			self.config.toolBarId = self.getParmByAttr("toolBarId");								//工具栏模版id，优先级大于url
			self.config.toolBarUrl = self.getParmByAttr("toolBarUrl");							//工具栏模版url
			self.config.minHeight = self.getParmByAttr("minHeight");								//表格内容区域的最小高度，默认最小140px
			self.config.outTime = self.getParmByAttr("outTime") || 10000;						//数据加载的最长时间，默认10s，在这个时间内，会不停的执行setInterval方法来使表格自适应
			self.config.intervalTime = self.getParmByAttr("intervalTime") || 500;		//setinterval方法时间间隔，默认500ms
		},
		//获取对象的类样式
		getClass:function(){
			var self = this;
			this.classes =  $(self.target).attr("class");
		},
		//获取对象的Id
		getId:function(){
			var self = this;
			this.id =  $(self.target).attr("id");
		},
		//创建表格标题
		creatCaption:function(){
			var self = this;
			var ctable = $("<table></table>");
			ctable.addClass(self.classes);
			ctable.append(self.target.find("caption").clone());
			self.caption.append(ctable);
		},
		//创建thead
		creatHeader:function(){
			var self = this;
			var htable = $("<table></table>");
			htable.addClass(self.classes);
			htable.append(self.target.find("thead").clone());
			self.header.append(htable);
		},
		//创建tbody
		creatBody:function(){
			var self = this,
					tbody = $("<table></table>");
			tbody.addClass(self.classes);
			tbody.attr("id",self.id);
			tbody.append(self.target.html());
			self.body.append(tbody);
		},
		//创建tfoot
		creatFooter:function(){
			var self = this;
			var ftable = $("<table></table>");
			ftable.addClass(self.classes);
			ftable.append(self.target.find("tfoot").clone());
			self.footer.append(ftable);
		},
		//根据模版设置分页栏
		creatPagination:function(cb){
			var self = this;
			var paginationTmp = ""
			if(self.config.paginationId){
				paginationTmp = $("#"+self.config.paginationId).html();
				self.pagination.append(paginationTmp);
			}else if(self.config.paginationUrl){
				$.ajax({
					type:"get",
					url:self.config.paginationUrl,
					success:function(data){
						paginationTmp = data;
						self.pagination.append(paginationTmp);
					}
				});
			}
			
		},
		//根据id创建工具栏
		creatToolBar:function(){
			var self = this;
			var toolBarIdTmp = "";
			var toolBarId = self.config.toolBarId;
			if(toolBarId){
				toolBarIdTmp = $("#"+toolBarId).html();
				self.toolbar.html(toolBarIdTmp);
				//移除工具栏模版
				$("#"+toolBarId).remove();
			}else if(self.config.toolBarUrl){
				$.ajax({
					type:"get",
					url:self.config.toolBarUrl,
					success:function(data){
						toolBarIdTmp = data;
						self.toolbar.html(toolBarIdTmp);
					}
				});
			}
		},
		
		iniTable:function(){
			var self = this;
			self.target.removeAttr("data-initable");
			
			//根据原table的id设置tableWraper的id
			self.tableWraperId = "tableWraper_"+self.id ;
			self.tableWraper.attr("id",self.tableWraperId);
			self.target.wrap(self.tableWraper);
			
			self.target.wrap(self.container);
			
			//创建内容区
			self.target.wrap(self.body);
			
			//创建header html
			if(self.hasThead){
				self.target.find("thead").css({
					"visibility":"hidden"
				});
				
				self.creatHeader();
				self.target.parent().before(self.header);
				
				self.header.find("thead").css({
					"visibility":"visible"
				});
				
				//绑定全选功能
				self.header.find("tr").each(function(){
					if($(this).find("th:first input[type='checkbox']").length){
						$(this).find("th:first input[type='checkbox']").addClass(OTable.CHECKBOX_CLASS.headCheckBox);
					}
				});
			}
			
			
			//创建tfoot
			if(self.hasTfoot){
				//将原table的tfoot设置隐藏
				self.target.find("tfoot").css({
					"visibility":"hidden"
				});
				//创建footer html，并设置可见
				self.creatFooter();
				self.footer.find("tfoot").css({
					"visibility":"visible"
				});
				self.target.parent().after(self.footer);
			}
			
			//创建工具栏
			self.creatToolBar();
			self.target.parent().parent().before(self.toolbar);
			
			//创建caption
			if(self.hasCaption){
				self.creatCaption();
				self.target.parent().parent().before(self.caption);
			}
			
			//清除浮动
			self.target.parent().parent().after("<div class='clearfix'></div>");
			//创建分页栏
			self.creatPagination();
			self.target.parent().parent().after(self.pagination);
			
			self.body.find("tfoot").css({
				"visibility":"hidden"
			});
			
			self.target.parent().find("thead tr").each(function(){
				if($(this).find("th:first input[type='checkbox']").length){
					$(this).find("th:first input[type='checkbox']").addClass(OTable.CHECKBOX_CLASS.headTriggerCheckBox);
				}
			});
			

			self.winResize();
			self.events();
			//表头，表尾的定时自适应
			self.timer = "";
			self.timer = setInterval(function(){
				self.initResize();
			},self.config.intervalTime);
			setTimeout(function(){
				clearInterval(self.timer);
			},self.config.outTime);
		},
		//重置表格，自适应
		initResize:function(){
			var self = this,
				id = self.tableWraperId,
				toolbar = self.toolbar,
				container = self.target.parent().parent(),
				header = self.header,
				body = self.target.parent(),
				footer = self.footer,
				pagination = self.pagination;
			
			var tableJson = {};
			var basicTable = $("#"+self.id);
			//表格的宽度
			tableJson.width = basicTable.width()+2;
			//caption的高度
			tableJson.captionH = basicTable.find("caption").outerHeight();
			//thead的整体高度
			tableJson.theadH =  basicTable.find("thead").outerHeight();
			//tfoot的整体高度
			tableJson.tfootH =  basicTable.find("footer").outerHeight();
			
			//toolBar的高度
			var toolbarH = toolbar.outerHeight();
			//pagination的高度
			var paginationH = pagination.outerHeight();
			body.css({"margin-top":tableJson.theadH});
			
			if(self.config.height){
				body.css({
					"height":self.config.height - tableJson.captionH - tableJson.theadH - toolbarH - paginationH - 4 
				})
			};
			
			if(self.config.minHeight){
				body.css({
					"min-height":parseInt(self.config.minHeight)
				})
			};
			//如果设置了最小高度
			
			self.initHeader();
			
			self.initFooter();
					
			//绑定是否全选
			body.find("tbody tr").each(function(i){
				if($(this).find("td:first input[type='checkbox']").length){
					$(this).find("td:first input[type='checkbox']").addClass(OTable.CHECKBOX_CLASS.bodyCheckBox);
				};
			});
			
		},
		//header自适应
		initHeader:function(){
			var self = this,
					header = self.header
			var basicTable = $("#"+self.id);
			var tableJson = {};
			//表格的宽度
			tableJson.width = basicTable.width()+2;
			//caption的高度
			tableJson.captionH = basicTable.find("caption").outerHeight();
			//thead的整体高度
			tableJson.theadH =  basicTable.find("thead").outerHeight();
			//thead的行宽度和高度
			var theadArr = [];
			basicTable.find("thead tr").each(function(){
				var trJson = {};
				var thArr = [];
				$(this).children("th").each(function(n){
					thArr.push($(this).outerWidth());
				});
				trJson.height = $(this).outerHeight();
				trJson.ths = thArr;
				theadArr.push(trJson);
			});
			
			header.css({"width":tableJson.width});
			basicTable.css({"margin-top":-tableJson.theadH - tableJson.captionH});
			var newHeadTable = header.find("table");
			newHeadTable.find("tr").each(function(n){
				var trData = theadArr[n];
				$(this).css({
					"height":trData.height
				})
				$(this).children("th").each(function(m){
					$(this).css({
						"width":trData.ths[m]
					})
				});
			});
		},
		//footer自适应
		initFooter:function(){
			var self = this,
					footer = self.footer;
			var basicTable = $("#"+self.id);
			var tableJson = {};
			//表格的宽度
			tableJson.width = basicTable.width()+2;
			tableJson.tfootH = basicTable.find("tfoot").outerHeight();
			//thead的行宽度和高度
			var tfootArr = [];
			basicTable.find("tfoot tr").each(function(){
				var trJson = {};
				var thArr = [];
				$(this).children("td").each(function(){
					thArr.push($(this).outerWidth());
				});
				trJson.height = $(this).outerHeight();
				trJson.ths = thArr;
				tfootArr.push(trJson);
			});
			
			footer.css({
				"width":tableJson.width
			});
			var newHeadTable = footer.find("table");
			newHeadTable.find("tr").each(function(n){
				var trData = tfootArr[n];
				/*$(this).css({
					"height":trData.height
				})*/
				$(this).children("td").each(function(m){
					$(this).css({
						"width":trData.ths[m]
					})
				});
			});
		},
		//窗口改变，表格自适应
		winResize:function(){
			var self = this;
			self.timeout = "";
			$(window).on("resize",function(){
				clearTimeout(self.timeout);
				self.timeout = setTimeout(function(){
					self.config.height = $("#"+self.tableWraperId+" .maxTable_body table").attr("data-height");
			//		self.initResize();
					
					//表头，表尾的定时自适应
					self.timer = "";
					self.timer = setInterval(function(){
						self.initResize();
					},self.config.intervalTime);
					setTimeout(function(){
						clearInterval(self.timer);
					},self.config.outTime);
					
					
					
				},self.config.intervalTime);
			})
		},
		//刷新，根据参数
		
		reflesh:function(height){
			this.config.height = height;
			this.target.attr("data-height",height);
			this.initResize();
		},
		events:function(){
			var self = this;
			//绑定全选
			if(self.hasThead){
				
				
				self.header.find("thead *").each(function(){
					$(this).removeAttr("onclick onchange ondblClick id").off();
				});
				
				$(document).on("click","#"+self.tableWraperId+" .maxTable_header thead *:not(input[type='checkbox']."+OTable.CHECKBOX_CLASS.headCheckBox+")",function(e){
					var ev = e || window.event;
					ev.preventDefault()
					ev.stopPropagation();
					var par = $(this).parents("#"+self.tableWraperId);
					var index = $(this).index("#"+self.tableWraperId+" .maxTable_header thead *:not(input[type='checkbox']."+OTable.CHECKBOX_CLASS.headCheckBox+")");
					console.log("index1--->"+index)
					par.find(".maxTable_body thead *:not(input[type='checkbox']."+OTable.CHECKBOX_CLASS.headTriggerCheckBox+")").eq(index).trigger("click");
				});
				
				
				$(document).on("click","#"+self.tableWraperId+" input[type='checkbox']."+OTable.CHECKBOX_CLASS.headCheckBox,function(e){
					var ev = e || window.event;
					ev.stopPropagation();
					var par = $(this).parents("#"+self.tableWraperId);
					var index = $(this).index("#"+self.tableWraperId+" .maxTable_header table input[type='checkbox']."+OTable.CHECKBOX_CLASS.headCheckBox);
					console.log("index2-->"+index);
					par.find(".maxTable_body table thead input[type='checkbox']."+OTable.CHECKBOX_CLASS.headTriggerCheckBox).eq(index).trigger("click");
					self.methods.checkAll.call(self,this);
				});
			}
			
			//绑定是否全选
			$(document).on("click","input[type='checkbox']."+OTable.CHECKBOX_CLASS.bodyCheckBox,function(){
				self.methods.isCheckAll.call(self,this);
			});
		},
		methods:{
			
			//多选框全选
			checkAll:function(obj){
				var self = this;
				var headCheckBox = $(obj);
				var checked = headCheckBox.prop("checked");
				var par = $(obj).parents("#"+self.tableWraperId);
				par.find("tbody input[type]."+OTable.CHECKBOX_CLASS.bodyCheckBox).each(function(){
					$(this).prop("checked",checked);
				});
			},
			//是否全选
			isCheckAll:function(obj){
				var self = this;
				var checked = $(obj).prop("checked");
				var par = $(obj).parents("#"+self.tableWraperId);
				if(!checked){
					par.find("input[type]."+OTable.CHECKBOX_CLASS.headCheckBox).prop("checked",false);
				}else{//判断是否有为选中的项
					var mark = true;
					par.find("tbody input[type]."+OTable.CHECKBOX_CLASS.bodyCheckBox).each(function(){
						if (!$(this).prop("checked")) {
							mark = false;
						}
						if(!mark){
							return false;
						}
					});
					par.find("input[type]."+OTable.CHECKBOX_CLASS.headCheckBox).prop("checked",mark);
				}
			}
		}
	};
	
	win.MaxTable = OTable;
	
	win.MaxTableInit = function(collection){
		if(!collection){
			collection = $("table[data-initable='yes']");
		}
		collection.each(function(){
			new OTable($(this));
		});
	};
	
})(window,jQuery);
